import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg';
const path = require('path');

export default (appInfo: EggAppInfo) => {
  const config = {} as PowerPartial<EggAppConfig>;

  // 应用密钥
  config.keys = appInfo.name + '_1640995200000_1234';

  // 中间件配置
  config.middleware = ['errorHandler'];

  config.host = 'http://luckstart.cn:7001/';

  config.multipart = {
    mode: 'file', // 文件模式
    fileSize: '10mb', // 文件大小限制
    fields: 2000,     // 允许的非文件字段数量
    files: 50,        // 允许的文件数量
    whitelist: ['.jpg', '.jpeg', '.png'], // 允许的文件类型
  };

  // 文件存放路径和文件白名单
  config.uploadPathMap = {
    uploadAvatarDir: '../uploadFiles/avatar', // 用户头像存储路径,
    uploadComRestaurantsDir: '../uploadFiles/comRestaurants', // 美食店
    exclusive_restaurants: '../uploadFiles/exclusiveRestaurants', // 专属餐厅
    exclusive_restaurants_dish: '../uploadFiles/exclusiveRestaurantsDish', // 专属餐厅菜品
  };

  // 文件静态路径
  config.static = {
    prefix: '/uploadFiles', // 访问前缀
    dir: path.join(appInfo.baseDir, '../uploadFiles'),
    dynamic: true,
    preload: false,
    maxAge: 31536000,
    buffer: true,
  };

  // JWT 配置
  config.jwt = {
    secret: 'luck-play-jwt-secret-key-2023',
    sign: {
      expiresIn: '7d',
    },
  };

  // JWT 中间件配置
  config.jwtAuth = {
    ignore: [
      '/',
      '/health',
      '/auth/register',
      '/auth/login',
      '/tags',
    ],
  };

  // 数据库配置 (暂时注释，避免启动时连接数据库)
  config.sequelize = {
    dialect: 'mysql',
    host: '127.0.0.1',
    port: 3306,
    database: 'database_egg_luck_paly',
    username: 'egg_luck_paly',
    password: 'jaling530',
    timezone: '+08:00',
    dialectOptions: {
      dateStrings: true,
      typeCast: true,
    },
    define: {
      freezeTableName: true,
      underscored: true,
      timestamps: true,
      createdAt: 'created_at',
      updatedAt: 'updated_at',
    },
  };

  // Redis 配置 (暂时注释)
  // config.redis = {
  //   client: {
  //     port: 6379,
  //     host: '127.0.0.1',
  //     password: '',
  //     db: 0,
  //   },
  // };

  // 表单验证配置
  config.validate = {
    convert: true,
    widelyUndefined: true,
  };

  // 安全配置
  config.security = {
    csrf: {
      enable: false,
    },
    domainWhiteList: ['*'],
  };

  // CORS 配置
  config.cors = {
    origin: '*',
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH',
  };

  // 错误处理中间件配置
  config.errorHandler = {
    enable: true,
  };

  // JWT 认证中间件配置
  config.jwtAuth = {
    enable: true,
    ignore: [
      '/health',
      '/auth/login',
      '/auth/register',
      '/restaurants',
      '/restaurants/:id',
      '/comments/:restaurantId',
    ],
  };

  return {
    ...config,
  };
};